package com.workingpub.commons.jdbc.builder.internal;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.workingpub.commons.jdbc.binding.IfEntry;
import com.workingpub.commons.jdbc.builder.BuildContext;
import com.workingpub.commons.jdbc.builder.LogicResolver;
import com.workingpub.commons.jdbc.builder.ResolverFactory;
import com.workingpub.commons.jdbc.builder.ognl.OgnlEvaluator;

@Service
public class IfResolver implements LogicResolver {

	@Autowired
	private ResolverFactory resolverFactory;

	@Override
	public List<Object> getContext(BuildContext buildContext, Object logicEntry) {
		if (logicEntry instanceof IfEntry) {
			IfEntry ifEntry = (IfEntry) logicEntry;
			Assert.isTrue(StringUtils.hasText(ifEntry.getTest()), "The test text is null or empty");
			if (OgnlEvaluator.evaluateBoolean(ifEntry.getTest(), buildContext.getRootParameter(),
					buildContext.getOtherParameters())) {
				return resolverFactory.resolve(buildContext, ifEntry.getContent().toArray());
			}
		}
		return null;
	}

}
